package com.aiou.security.app.handler;

import com.aiou.security.app.authentication.DefaultAuthenticationFailureHandler;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.provider.error.DefaultOAuth2ExceptionRenderer;
import org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint;
import org.springframework.security.oauth2.provider.error.OAuth2ExceptionRenderer;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author: zyb
 * @date: 2018-08-20 14:47
 */
@Slf4j
public class CustomAuthenticationEntryPoint extends OAuth2AuthenticationEntryPoint {
    private HandlerExceptionResolver handlerExceptionResolver = new DefaultHandlerExceptionResolver();
    private OAuth2ExceptionRenderer exceptionRenderer = new DefaultOAuth2ExceptionRenderer();


    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        String message = DefaultAuthenticationFailureHandler.errorMessage.get();
        if (message == null) {
            doHandle(request, response, authException);
            return;
        }

        LoginFailureResponse failureResponse = new LoginFailureResponse(request.getServletPath(), message);
        ResponseEntity<LoginFailureResponse> responseEntity = new ResponseEntity<>(failureResponse, HttpStatus.FORBIDDEN);
        try {
            log.info("authException:{}.", authException);
            exceptionRenderer.handleHttpEntityResponse(responseEntity, new ServletWebRequest(request, response));
            response.flushBuffer();
        } catch (ServletException e) {
            // Re-use some of the default Spring dispatcher behaviour - the exception came from the filter chain and
            // not from an MVC handler so it won't be caught by the dispatcher (even if there is one)
            if (handlerExceptionResolver.resolveException(request, response, this, e) == null) {
                throw e;
            }
        } catch (IOException | RuntimeException e) {
            throw e;
        } catch (Exception e) {
            // Wrap other Exceptions. These are not expected to happen
            throw new RuntimeException(e);
        }
    }

    @NoArgsConstructor
    @Data
    public static class LoginFailureResponse {

        /**
         * timestamp : 1534748353158
         * status : 403
         * error : Forbidden
         * message : 用户名或密码错误！
         * path : /authentication/form
         */

        private long timestamp = System.currentTimeMillis();
        private int status = 403;
        private String error = "Forbidden";
        private String message;
        private String path;

        private LoginFailureResponse(String path, String message) {
            this.path = path;
            this.message = message;
        }
    }
}
